<template>
  <div class="receipt-detail">
    <!-- 筛选表单 -->
    <el-form :model="filter" inline class="filter-form">
      <!-- 时间范围 -->
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="filter.createTime"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          default-time="[00:00:00, 23:59:59]"
        />
      </el-form-item>

      <!-- 交易状态（单选下拉） -->
      <el-form-item label="交易状态">
        <el-select
          v-model="filter.tradeStatus"
          placeholder="请选择交易状态"
          clearable
        >
          <el-option
            v-for="item in tradeStatusOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 支付渠道（单选下拉） -->
      <el-form-item label="支付渠道">
        <el-select
          v-model="filter.payChannel"
          placeholder="请选择支付渠道"
          clearable
        >
          <el-option
            v-for="item in payChannelOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 支付类型（单选下拉） -->
      <el-form-item label="支付类型">
        <el-select
          v-model="filter.payType"
          placeholder="请选择支付类型"
          clearable
        >
          <el-option
            v-for="item in payTypeOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 交易类型（单选下拉） -->
      <el-form-item label="交易类型">
        <el-select
          v-model="filter.tradeType"
          placeholder="请选择交易类型"
          clearable
        >
          <el-option
            v-for="item in tradeTypeOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 商户单号 -->
      <el-form-item label="商户单号">
        <el-input v-model="filter.merchantNo" placeholder="请输入商户单号" />
      </el-form-item>

      <!-- 关联收款单号 -->
      <el-form-item label="关联收款单号">
        <el-input
          v-model="filter.relatedReceiptNo"
          placeholder="请输入关联收款单号"
        />
      </el-form-item>

      <!-- 单据编号 -->
      <el-form-item label="单据编号">
        <el-input v-model="filter.docNo" placeholder="请输入单据编号" />
      </el-form-item>

      <!-- 核销单号 -->
      <el-form-item label="核销单号">
        <el-input v-model="filter.writeOffNo" placeholder="请输入核销单号" />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="queryData">查询</el-button>
        <el-button type="success" @click="exportData">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%"
      :empty-text="''"
      :scroll="{ x: 'max-content' }"
    >
      <!-- 操作列 -->
      <el-table-column label="操作" width="80">
        <template #default="scope">
          <el-button type="text" size="mini" @click="handleView(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>

      <!-- 核心字段 -->
      <el-table-column prop="docNo" label="单据编号" min-width="120" />
      <el-table-column
        prop="payAmount"
        label="支付金额"
        min-width="120"
        align="right"
      >
        <template #default="scope"
          >¥{{ scope.row.payAmount.toFixed(2) }}</template
        >
      </el-table-column>
      <el-table-column prop="fee" label="手续费" min-width="120" align="right">
        <template #default="scope">¥{{ scope.row.fee.toFixed(2) }}</template>
      </el-table-column>
      <el-table-column
        prop="arrivalAmount"
        label="到账金额"
        min-width="120"
        align="right"
      >
        <template #default="scope"
          >¥{{ scope.row.arrivalAmount.toFixed(2) }}</template
        >
      </el-table-column>
      <el-table-column prop="createTime" label="订单创建时间" min-width="160" />
      <el-table-column prop="tradeType" label="交易类型" min-width="120" />
      <el-table-column prop="tradeStatus" label="交易状态" min-width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.tradeStatus)">
            {{ scope.row.tradeStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="errorReason" label="错误原因" min-width="150" />
      <el-table-column
        prop="completeTime"
        label="订单完成时间"
        min-width="160"
      />

      <!-- 关联字段 -->
      <el-table-column
        prop="relatedReceiptNo"
        label="关联收款单号"
        min-width="150"
      />
      <el-table-column
        prop="relatedOrderNo"
        label="关联要货单号"
        min-width="150"
      />
      <el-table-column
        prop="relatedExpenseNo"
        label="关联其他支出单号"
        min-width="180"
      />
      <el-table-column prop="writeOffNo" label="核销单号" min-width="150" />
      <el-table-column prop="merchantNo" label="商户单号" min-width="150" />
      <el-table-column prop="tradeNo" label="交易单号" min-width="180" />

      <!-- 支付信息 -->
      <el-table-column prop="payType" label="支付类型" min-width="120" />
      <el-table-column prop="payChannel" label="支付渠道" min-width="120" />
      <el-table-column prop="settleAccount" label="结算账户" min-width="150" />
      <el-table-column prop="settleMethod" label="结算方式" min-width="120" />
      <el-table-column prop="orderDesc" label="订单描述" min-width="150" />
      <el-table-column prop="randomCode" label="随机码" min-width="150" />
      <el-table-column
        prop="platformUser"
        label="支付平台用户标识"
        min-width="180"
      />

      <!-- 退款信息 -->
      <el-table-column prop="loanFlag" label="借贷标识" min-width="120" />
      <el-table-column
        prop="refundTradeNo"
        label="退款交易流水号"
        min-width="180"
      />
      <el-table-column
        prop="refundCompleteTime"
        label="退款完成时间"
        min-width="160"
      />
      <el-table-column
        prop="refundErrorReason"
        label="退款错误原因"
        min-width="150"
      />
    </el-table>

    <!-- 空状态 -->
    <div v-if="tableData.length === 0" class="empty-state">
      <el-empty description="暂无数据" />
    </div>

    <!-- 分页组件 -->
    <div v-if="total > 0" class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElTable,
  ElTableColumn,
  ElTag,
  ElEmpty,
  ElPagination,
  ElMessage,
} from "element-plus";

// 筛选条件
const filter = reactive({
  createTime: null, // 日期范围
  tradeStatus: "", // 交易状态（单选）
  payChannel: "", // 支付渠道（单选）
  payType: "", // 支付类型（单选）
  tradeType: "", // 交易类型（单选）
  merchantNo: "", // 商户单号
  relatedReceiptNo: "", // 关联收款单号
  docNo: "", // 单据编号
  writeOffNo: "", // 核销单号
});

// 下拉选项定义
const tradeStatusOptions = ["交易成功", "交易不存在", "交易失败", "交易处理中"];
const payChannelOptions = ["通联支付", "支付宝", "微信支付", "银联"];
const payTypeOptions = ["收款", "退款", "撤销", "空"];
const tradeTypeOptions = ["微信", "QQ", "支付宝", "银联", "空"];

// 表格数据 & 分页
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 查询数据（模拟）
const queryData = () => {
  console.log("查询参数：", filter);

  // 模拟接口请求（实际项目中替换为真实API调用）
  setTimeout(() => {
    // 生成模拟数据
    tableData.value = generateMockData(10);
    total.value = 50;
    ElMessage.success("查询成功");
  }, 500);
};

// 导出数据（模拟）
const exportData = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning("暂无数据可导出");
    return;
  }

  // 模拟导出（实际项目中调用导出API）
  ElMessage.info("开始导出数据...");
};

// 查看详情（模拟）
const handleView = (row) => {
  console.log("查看详情:", row);
  ElMessage.info(`查看单据 ${row.docNo} 详情`);
  // 实际项目中可打开详情弹窗或跳转详情页
};

// 交易状态标签类型映射
const getStatusTagType = (status) => {
  switch (status) {
    case "交易成功":
      return "success";
    case "交易失败":
      return "danger";
    case "交易处理中":
      return "warning";
    default:
      return "info";
  }
};

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val;
  queryData();
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  queryData();
};

// 生成模拟数据
const generateMockData = (count) => {
  const statusList = ["交易成功", "交易处理中", "交易失败"];
  const tradeTypes = ["微信", "支付宝", "银联"];
  const payTypes = ["收款", "退款", "撤销"];

  return Array.from({ length: count }).map((_, index) => {
    const status = statusList[Math.floor(Math.random() * statusList.length)];
    const amount = Math.random() * 1000 + 10;
    const fee = amount * (Math.random() * 0.03);

    return {
      id: index + 1,
      docNo: `ZSKD${20250601 + index}`,
      payAmount: amount,
      fee: fee,
      arrivalAmount: amount - fee,
      createTime: `2025-06-${Math.floor(Math.random() * 26) + 1} ${Math.floor(
        Math.random() * 24
      )}:${Math.floor(Math.random() * 60)}:${Math.floor(Math.random() * 60)}`,
      tradeType: tradeTypes[Math.floor(Math.random() * tradeTypes.length)],
      tradeStatus: status,
      errorReason: status === "交易失败" ? "支付超时" : "",
      completeTime: `2025-06-${Math.floor(Math.random() * 26) + 1} ${Math.floor(
        Math.random() * 24
      )}:${Math.floor(Math.random() * 60)}:${Math.floor(Math.random() * 60)}`,
      relatedReceiptNo: `SKDH${Math.floor(Math.random() * 100000)}`,
      relatedOrderNo: `YHDH${Math.floor(Math.random() * 100000)}`,
      relatedExpenseNo: `ZC${Math.floor(Math.random() * 100000)}`,
      writeOffNo: `HX${Math.floor(Math.random() * 100000)}`,
      merchantNo: `SH${Math.floor(Math.random() * 10000000)}`,
      tradeNo: `JY${Math.floor(Math.random() * 1000000000)}`,
      payType: payTypes[Math.floor(Math.random() * payTypes.length)],
      payChannel: "通联支付",
      settleAccount: "支付宝",
      settleMethod: "即时到账",
      orderDesc: "商品销售",
      randomCode: `RC${Math.floor(Math.random() * 100000)}`,
      platformUser: `USER${Math.floor(Math.random() * 10000)}`,
      loanFlag: "借",
      refundTradeNo:
        status === "退款" ? `TK${Math.floor(Math.random() * 1000000)}` : "",
      refundCompleteTime:
        status === "退款"
          ? `2025-06-${Math.floor(Math.random() * 26) + 1} ${Math.floor(
              Math.random() * 24
            )}:${Math.floor(Math.random() * 60)}:${Math.floor(
              Math.random() * 60
            )}`
          : "",
      refundErrorReason: "",
    };
  });
};

// 初始化加载
onMounted(() => {
  // 设置默认时间范围为近7天
  const today = new Date();
  const weekAgo = new Date();
  weekAgo.setDate(today.getDate() - 7);

  filter.createTime = [
    weekAgo.toISOString().split("T")[0],
    today.toISOString().split("T")[0],
  ];

  // 初始查询
  queryData();
});
</script>

<style scoped>
.receipt-detail {
  padding: 24px;
  background: #fff;
}

.filter-form {
  margin-bottom: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-form .el-form-item {
  margin-bottom: 0;
}

.filter-form .el-input,
.filter-form .el-select {
  width: 180px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

/* 表格样式优化 */
.el-table__header th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.el-table__body-wrapper {
  overflow-x: auto;
}
</style>